<template>
    <div>
      <!--      面包屑导航区域-->
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
      </el-breadcrumb>
<!--      卡片视图-->
      <el-card>
<!--        添加角色列表区域-->
        <el-row>
          <el-col>
            <el-button @click="addDialogVisible=true" type="primary">添加角色</el-button>
          </el-col>
        </el-row>
<!--        角色列表区域-->
        <el-table :data="rolelist" border stripe>
<!--          展开列-->
          <el-table-column type="expand">
            <template slot-scope="scope">
<!--              <pre>-->
<!--                {{scope.row}}-->
<!--              </pre>-->
              <el-col
                :class="['vcenter','bdBottom', i1 === 0 ? 'bdTop' : '']"
                v-for="(item1,i1) in scope.row.children"
                :key="item1.id">
<!--                渲染一级权限-->
                <el-col :span="5">
                  <el-tag
                    @close="removeRightById(scope.row, item1.id)"
                    closable>{{item1.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
<!--                渲染二级和三级权限-->
                <el-col :span="19">
<!--                  通过for循环 嵌套循环渲染二级权限-->
                  <el-row
                    :class="['vcenter',i2 === 0 ? '' : 'bdTop']"
                    v-for="(item2,i2) in item1.children"
                    :key="item2.id">
                    <el-col :span="6">
                      <el-tag
                        @close="removeRightById(scope.row, item2.id)"
                        closable
                        type="success">{{item2.authName}}</el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <!--                渲染三级权限-->
                    <el-col :span="18">
                      <el-tag
                        @close="removeRightById(scope.row, item3.id)"
                        closable
                        type="warning"
                        v-for="item3 in item2.children"
                        :key="item3.id">
                        {{item3.authName}}
                      </el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-col>
            </template>
          </el-table-column>
<!--          索引列-->
          <el-table-column type="index"></el-table-column>
          <el-table-column label="角色名称" prop="roleName"></el-table-column>
          <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
          <el-table-column label="操作" width="300px">
            <template slot-scope="scope">
              <el-button @click="showEditDialog(scope.row.id)" size="mini" type="primary" icon="el-icon-search">编辑</el-button>
              <el-button @click="delRolesById(scope.row.id)" size="mini" type="danger" icon="el-icon-delete">删除</el-button>
              <el-button @click="showSetRightDialog(scope.row)" size="mini" type="warning" icon="el-icon-setting">分配权限</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
<!--      添加角色对话框-->
      <el-dialog
        @close="addFormClose"
        title="添加角色"
        :visible.sync="addDialogVisible"
        width="50%">
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRoles">确 定</el-button>
        </span>
      </el-dialog>
<!--      修改角色对话框-->
      <el-dialog
        @close="editFormClose"
        title="添加角色"
        :visible.sync="editDialogVisible"
        width="50%">
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef">
          <el-form-item label="角色ID" prop="roleId">
            <el-input v-model="editForm.roleId" disabled></el-input>
          </el-form-item>
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editRoles">确 定</el-button>
        </span>
      </el-dialog>
<!--      分配权限对话框-->
      <el-dialog
        @close="setRightDialogClosed"
        title="分配权限"
        :visible.sync="setRightDialogVisible"
        width="50%">
<!--        树形控件-->
        <el-tree
          ref="treeRef"
          show-checkbox
          :default-checked-keys="defKeys"
          :data="rightsList"
          :props="treeProps"
          default-expand-all
          node-key="id"></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRightDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights">确 定</el-button>
        </span>
      </el-dialog>
    </div>
</template>

<script>
export default {
  name: 'Roles',
  data () {
    return {
      // 所有角色列表数据
      rolelist: [],
      // 添加角色对话框显示与隐藏
      addDialogVisible: false,
      // 添加角色列表
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添加角色规则
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      // 修改角色对话框
      editDialogVisible: false,
      // 修改角色数据列表
      editForm: {
        roleId: '',
        roleName: '',
        roleDesc: ''
      },
      // 修改角色规则
      editFormRules: {
        roleId: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      // 控制分配权限对话框的显示与隐藏
      setRightDialogVisible: false,
      // 所有权限数据
      rightsList: [],
      // 树形控件数据绑定对象
      treeProps: {
        // 看到的值
        label: 'authName',
        // 嵌套
        children: 'children'
      },
      // 默认选中的节点id数值
      defKeys: [],
      // 当前即将分配权限的角色id
      roleId: ''
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    // 获取所有角色列表
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolelist = res.data
      console.log(this.rolelist)
      this.$message.success('获取角色列表成功')
    },
    // 添加角色
    addRoles () {
      this.$refs.addFormRef.validate(async valid => {
        console.log(valid)
        if (!valid) return false
        const { data: res } = await this.$http.post('roles/', this.addForm)
        console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败')
        }
        this.addDialogVisible = false
        this.getRolesList()
        this.$message.success('添加角色成功')
      })
    },
    // 添加角色对话框关闭
    addFormClose () {
      this.$refs.addFormRef.resetFields()
    },
    // 删除角色
    async delRolesById (id) {
      console.log(id)
      // 弹窗询问是否删除
      var confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消删除角色')
      }
      // 确认删除
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败')
      }
      this.getRolesList()
      this.$message.success('删除角色成功')
    },
    // 显示修改角色对话框
    async showEditDialog (id) {
      console.log(id)
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色信息失败')
      }
      this.$message.success('获取角色信息成功')
      this.editForm = res.data
      console.log(this.editForm)
      this.editDialogVisible = true
    },
    // 修改角色对话框关闭
    editFormClose () {
      this.$refs.editFormRef.resetFields()
    },
    // 修改角色
    editRoles () {
      this.$refs.editFormRef.validate(async valid => {
        console.log(valid)
        if (!valid) return false
        const { data: res } = await this.$http.put('roles/' + this.editForm.roleId, {
          roleName: this.editForm.roleName,
          roleDesc: this.editForm.roleDesc
        })
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('修改角色失败')
        }
        this.editDialogVisible = false
        this.getRolesList()
        this.$message.success('修改角色成功')
      })
    },
    // 根据id删除对应的权限
    async removeRightById (role, rightid) {
      console.log(role)
      console.log(rightid)
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('用户取消删除')
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightid}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败')
      }
      this.$message.success('删除权限成功')
      // this.getRolesList()
      // 防止列表刷新
      role.children = res.data
    },
    // 显示分配权限对话框
    async showSetRightDialog (role) {
      this.roleId = role.id
      // 获取所有权限数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限树失败')
      }
      this.$message.success('获取权限树成功')
      this.rightsList = res.data
      console.log(this.rightsList)
      // 递归获取三级节点id
      this.getLeafKeys(role, this.defKeys)
      this.setRightDialogVisible = true
    },
    // 通过递归的形式，获取角色所有三级权限的id，并保存到defkeys数组中
    getLeafKeys (node, arr) {
      console.log(node)
      // 如果当前node节点不包含children属性 则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 监听权限对话框关闭事件
    setRightDialogClosed () {
      this.defKeys = []
    },
    // 点击为角色分配权限
    async allotRights () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      console.log(keys)
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.setRightDialogVisible = false
    }
  }
}
</script>

<style scoped lang="less">
.el-tag{
  margin: 7px;
}
.bdTop{
  border-top: 1px solid #eeeeee;
}
.bdBottom{
  border-bottom: 1px solid #eeeeee;
}
.vcenter{
  display: flex;
  align-items: center;
}
</style>
